package com.yanwq.sayhi.controller.user.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.yanwq.pulltorefreshview.view.PullToRefreshLayout;
import com.yanwq.pulltorefreshview.view.PullToRefreshListener;
import com.yanwq.sayhi.R;
import com.yanwq.sayhi.base.BaseFragment;
import com.yanwq.sayhi.common.client.MImageLoader;
import com.yanwq.sayhi.common.client.OkJsonObjectResponseCallback;
import com.yanwq.sayhi.common.client.OkRequestParams;
import com.yanwq.sayhi.common.client.OkRestClient;
import com.yanwq.sayhi.common.constant.CacheConstant;
import com.yanwq.sayhi.common.event.UserEvent;
import com.yanwq.sayhi.common.tool.CropTool;
import com.yanwq.sayhi.controller.user.UserMgr;
import com.yanwq.sayhi.controller.user.activity.MottoActivity;
import com.yanwq.sayhi.controller.user.activity.NicknameActivity;
import com.yanwq.sayhi.controller.user.activity.PasswordChangeActivity;
import com.yanwq.sayhi.controller.user.dialog.LogoutDialog;
import com.yanwq.sayhi.dao.bean.User;
import com.yanwq.sayhi.widget.MToast;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class UserFragment extends BaseFragment {
    @BindView(R.id.user_refresh)
    PullToRefreshLayout mRefreshLayout;
    @BindView(R.id.user_avatar)
    ImageView mAvatarV;
    @BindView(R.id.user_motto)
    TextView mottoV;
    @BindView(R.id.user_nickname)
    TextView nicknameV;
    @BindView(R.id.user_phone)
    TextView phoneV;

    @OnClick(R.id.user_logout)
    void logout() {
        new LogoutDialog(getActivity()).show();
    }

    @OnClick(R.id.user_avatar)
    void avatar() {
        mCropTool.pick(getActivity(), this);
    }

    @OnClick(R.id.user_motto_lyt)
    void motto() {
        Intent intent = new Intent(getActivity(), MottoActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.user_nickname_lyt)
    void nickname() {
        Intent intent = new Intent(getActivity(), NicknameActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.user_password_lyt)
    void password() {
        Intent intent = new Intent(getActivity(), PasswordChangeActivity.class);
        startActivity(intent);
    }

    private File mPhotoFile;
    private String mFileName;
    private CropTool mCropTool;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_user, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mCropTool.crop(mPhotoFile, getActivity(), this, requestCode, resultCode, data, new CropTool.CropCallback() {
            @Override
            public void onComplete(Uri resultUri) {
                mAvatarV.setImageURI(resultUri);
                uploadAvatar();
            }
        });
    }

    @SuppressWarnings("unused")
    public void onEvent(UserEvent event) {
        switch (event.getEventType()) {
            case UserEvent.UPDATE:
                refreshView();
                break;
            case UserEvent.LOGOUT:
                getActivity().finish();
                break;
        }
    }

    public void init() {
        mFileName = CacheConstant.getRandomFileName();
        mPhotoFile = new File(CacheConstant.getPhotoPath(), mFileName);
        mCropTool = new CropTool();
    }

    public void initView() {
        User user = UserMgr.get();
        MImageLoader.displayImage(user.getAvatarMediumUrl(), mAvatarV);
        mottoV.setText(user.getMotto());
        nicknameV.setText(user.getNickname());
        phoneV.setText(user.getPhone());

        mRefreshLayout.setPullToRefreshListener(new PullToRefreshListener() {
            @Override
            public void onRefresh() {
                getUser();
            }
        });
    }

    private void getUser() {
        User user = UserMgr.get();
        OkRestClient.getInstance().get(getActivity(), String.format("/user/find/%s", user.getUuid()), null, new OkJsonObjectResponseCallback() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                if (jsonObject == null) {
                    MToast.showShort(getActivity(), "用户不存在，请尝试重新登陆");
                    UserMgr.logout();
                    return;
                }
                UserMgr.update(jsonObject);
                refreshView();
            }

            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {
                mRefreshLayout.stopRefresh();
            }
        });
    }

    private void refreshView() {
        User user = UserMgr.get();
        MImageLoader.displayImage(user.getAvatarMediumUrl(), mAvatarV);
        mottoV.setText(user.getMotto());
        nicknameV.setText(user.getNickname());
        phoneV.setText(user.getPhone());
    }

    private void uploadAvatar() {
        OkRequestParams params = new OkRequestParams();
        params.put("mf", mFileName, mPhotoFile);

        OkRestClient.getInstance().post(getActivity(), "/oss/picture", params, new OkJsonObjectResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog("正在上传头像");
            }

            @Override
            public void onSuccess(JSONObject jsonObject) {
                requestUpdateAvatar(jsonObject);
            }

            @Override
            public void onFail(int status, String s, Throwable throwable) {
                super.onFail(status, s, throwable);
                cancelProgressDialog();
            }

            @Override
            public void onStop() {
            }
        });
    }

    private void requestUpdateAvatar(JSONObject avatar) {
        User user = UserMgr.get();
        user.setAvatarThumbUrl(avatar.getString("picThumbUrl"));
        user.setAvatarMediumUrl(avatar.getString("picMediumUrl"));
        user.setAvatarOriginUrl(avatar.getString("picOriginUrl"));

        OkRestClient.getInstance().post(getActivity(),
                "/user/update",
                user,
                new OkJsonObjectResponseCallback() {
                    @Override
                    public void onStart() {
                        showProgressDialog("正在修改头像");
                    }

                    @Override
                    public void onSuccess(JSONObject jsonObject) {
                        UserMgr.update(jsonObject);
                        MToast.showShort(getActivity(), "恭喜，新头像很嗨");
                    }

                    @Override
                    public void onStop() {
                        cancelProgressDialog();
                    }
                });
    }
}
